from contextlib import asynccontextmanager
from fastapi import FastAPI
from typing import AsyncIterator
import logging
import asyncio
from fastapi import FastAPI
from app.core.config import settings
from app.core.mysql import init_db

logger = logging.getLogger(__name__)


# 模拟数据库连接池

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    # ✅ 启动时执行
    """应用启动事件处理器"""
    logger.info(f"启动 {settings.PROJECT_NAME} v{settings.PROJECT_VERSION}")
    logger.info(f"环境: {settings.ENVIRONMENT}")
    
    # 这里可以添加应用启动时需要执行的代码
    # 例如: 初始化数据库连接池、加载配置等
    
    # 示例：初始化Redis连接（如果需要）
    if settings.REDIS_URL:
        try:
            # import aioredis
            from redis import asyncio as aioredis
            app.state.redis = await aioredis.from_url(settings.REDIS_URL)
            logger.info("Redis连接成功")
        except Exception as e:
            logger.error(f"Redis连接失败: {str(e)}")

    # 示例：启动RabbitMQ消费者（如果需要）
    if settings.RABBITMQ_URL:
        try:
            from app.core.worker import start_consumer
            app.state.rabbit_consumer_task = asyncio.create_task(start_consumer())
            logger.info("RabbitMQ消费者已启动")
        except Exception as e:
            logger.error(f"RabbitMQ消费者启动失败: {str(e)}")


    # 示例：初始化Tortoise ORM数据库连接
    app.state.tortoise = await init_db()
    # logger.info("Tortoise ORM数据库连接已初始化") 

    yield  # 应用在此运行

    # ✅ 关闭时执行
    print("🛑 应用关闭：正在释放数据库连接池...")
    # await db_pool.close()
    print("👋 资源已清理")